﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using U9BJWebApi.Models;
using static U9BJWebApi.Controllers.SentController;

namespace U9BJWebApi.Public
{
    public static class PublicMethod
    {
        public static ContextCode CheckContext(long OrgID,long UserID)
        {
            DataSet Orgds = DbHelperSQL.Query(@"select Code from Base_Organization where ID = '" + OrgID + "'");
            if (Orgds.Tables.Count == 0 || Orgds.Tables[0].Rows.Count == 0)
            {
                throw new System.Exception("找不到组织" + OrgID);
            }
            var OrgCode = Orgds.Tables[0].Rows[0]["Code"].ToString();

            DataSet Userds = DbHelperSQL.Query(@"select Code,Name from Base_User where ID ='" + UserID + "'");
            if (Userds.Tables.Count == 0 || Userds.Tables[0].Rows.Count == 0)
            {
                throw new System.Exception("找不到用户" + UserID);
            }
            var UserCode = Userds.Tables[0].Rows[0]["Code"].ToString();
            var UserName = Userds.Tables[0].Rows[0]["Name"].ToString();
            return new ContextCode 
            { 
                OrgCode = OrgCode, 
                UserCode = UserCode,
                UserName = UserName
            };
        }

        public static bool BarCodeRepeatCheck(List<string> barcodes)
        {
            var _redisClient = new RedisClient("localhost:6379");
            _redisClient.Password = "ufida@123";
            foreach (string barcode in barcodes)
            {
                if (!_redisClient.SetValueIfNotExists(barcode, "1"))
                {
                    return false;
                }
                _redisClient.Expire(barcode, 180);
            }
            return true;
        }

        public static string StringJoin(IEnumerable<string> args)
        {
            return string.Join(",", args.Select(t => $"'{t}'"));
        }
    }

    public class ContextCode
    {
        public string OrgCode { get; set; }
        public string UserCode { get; set; }
        public string UserName { get; set; }
    }
}